package com.byjh.api;


import com.byjh.app.dto.AuthDto;
import com.byjh.app.dto.EditUserDto;
import com.byjh.app.vo.UserVo;
import com.byjh.common.annotation.Anonymous;
import com.byjh.common.constant.Constants;
import com.byjh.common.constant.UserConstants;
import com.byjh.common.core.domain.R;
import com.byjh.common.core.domain.entity.SysUser;
import com.byjh.common.utils.SecurityUtils;
import com.byjh.common.utils.WechatUtils;
import com.byjh.common.config.WechatConfig;
import com.byjh.framework.web.service.SysLoginService;
import com.byjh.framework.web.service.SysRegisterService;
import com.byjh.system.service.ISysConfigService;
import com.byjh.system.service.ISysUserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Collections;
import java.util.Map;

@RestController
@RequestMapping("/api/login")
public class LoginApi {
    private final WechatConfig config;

    @Autowired
    public LoginApi(WechatConfig config) {
        this.config = config;
    }

    @Resource
    private ISysConfigService configService;

    @Resource
    private ISysUserService userService;

    @Resource
    private SysRegisterService registerService;

    @Resource
    private SysLoginService loginService;

    @SneakyThrows
    @PostMapping("/auth")
    @Anonymous
    public R<Map<String, Object>> auth(@RequestBody @Valid AuthDto dto) {
        String openId = WechatUtils.getOpenId(dto.getLoginCode(), config.getMiniProgram().getAppid(), config.getMiniProgram().getSecret());
        String token = configService.selectConfigByKey(Constants.WECHAT_TOKEN);
        String phone = WechatUtils.authenticatePhoneNumber(dto.getPhoneCode(), token);
        if (!userService.checkUserName(phone)) {
            registerService.register(phone, openId);
        }
        return R.ok(Collections.singletonMap(Constants.TOKEN, loginService.login(phone, UserConstants.DEFAULT_PASSWORD)));
    }

    @GetMapping("userInfo")
    public R<UserVo> userInfo() {
        Long userId = SecurityUtils.getUserId();
        return R.ok(userService.selectUserVoById(userId));
    }

    @PutMapping("/editUser")
    public R<String> editUser(@RequestBody @Validated EditUserDto dto) {
        SysUser user = new SysUser();
        user.setUserId(SecurityUtils.getUserId());
        user.setAvatar(dto.getAvatar());
        user.setNickName(dto.getNickName());
        user.setEmail(dto.getEmail());
        user.setPhonenumber(dto.getPhone());
        user.setSex(dto.getSex());
        int row = userService.updateUser(user);
        return row == 1 ? R.ok() : R.fail();
    }

}
